# Create your views here.
import smtplib
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from contact.models import ContactForm, MysiteCommon
from django.core.mail import EmailMessage, BadHeaderError
from django.core.mail import EmailMultiAlternatives, send_mail
from django.conf import settings
def index(request):
    mysiteOject = MysiteCommon()
    if request.method == 'POST':
        form =  ContactForm(request.POST)
        if form.is_valid():
            postdata = request.POST
            name = postdata.get('name', '')
            email = postdata.get('email', '')
            phone = postdata.get('phone', '')
            subject = postdata.get('subject', '')
            messages = postdata.get('messages', '')
            if subject and  messages:
                try:
                    to = mysiteOject.DEFAULT_TO_EMAIL
                    from_email =mysiteOject.DEFAULT_FROM_EMAIL
                    text_content = ''
                    html_content = '<p>Hi : Mysite.vn </p>'
                    html_content +='<ul>'
                    html_content +='<li> Name : %s </li>' % (name)
                    html_content +='<li> Email : %s </li>' % (email)
                    html_content +='<li> Phone : %s </li>' % (phone)
                    html_content +='</ul>'
                    html_content += '<br/> Subject : %s ' % (subject)
                    html_content += '<br/><br/> Message : %s ' % (messages)
                    msg = EmailMultiAlternatives(subject, text_content,from_email , [to])
                    msg.attach_alternative(html_content, "text/html")
                    msg.send()
                except BadHeaderError:
                    return HttpResponse('Error');
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()

    return render(request,'contact/index.html',{
        'form': form
    })
def thanks(request):
    return render(request, 'contact/thanks.html');